package com.lishem.carl._10dp;

/**
 * https://leetcode.cn/problems/edit-distance/description/
 * <p>
 * 给你两个单词 word1 和 word2， 请返回将 word1 转换成 word2 所使用的最少操作数  。
 * <p>
 * 你可以对一个单词进行如下三种操作：
 * <p>
 * 插入一个字符
 * <p>
 * 删除一个字符
 * <p>
 * 替换一个字符
 * <p>
 * 示例 1：
 * <p>
 * 输入：word1 = "horse", word2 = "ros"
 * <p>
 * 输出：3
 * <p>
 * 解释：
 * <p>
 * horse -> rorse (将 'h' 替换为 'r')
 * <p>
 * rorse -> rose (删除 'r')
 * <p>
 * rose -> ros (删除 'e')
 * <p>
 * 示例 2：
 * <p>
 * 输入：word1 = "intention", word2 = "execution"
 * <p>
 * 输出：5
 * <p>
 * 解释：
 * <p>
 * intention -> inention (删除 't')
 * <p>
 * inention -> enention (将 'i' 替换为 'e')
 * <p>
 * enention -> exention (将 'n' 替换为 'x')
 * <p>
 * exention -> exection (将 'n' 替换为 'c')
 * <p>
 * exection -> execution (插入 'u')
 */
public class _37LetCode72_编辑距离 {


    public int minDistance(String word1, String word2) {
        char[] chars1 = word1.toCharArray();
        char[] chars2 = word2.toCharArray();
        int[][] dp = new int[chars1.length + 1][chars2.length + 1];
        for (int i = 0; i <= chars1.length; i++) {
            dp[i][0] = i;
        }
        for (int i = 0; i <= chars2.length; i++) {
            dp[0][i] = i;
        }
        for (int i = 1; i <= chars1.length; i++) {
            for (int j = 1; j <= chars2.length; j++) {
                if (chars1[i - 1] == chars2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j] + 1, Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1));
                }
            }
        }
        return dp[chars1.length][chars2.length];
    }

    public static void main(String[] args) {
        _37LetCode72_编辑距离 sol = new _37LetCode72_编辑距离();
        System.out.println(sol.minDistance("horse", "ros"));
        System.out.println(sol.minDistance("intention", "execution"));
    }
}
